package guava;

import com.google.common.util.concurrent.*;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 通过guava对JDK提供的线程池进行装饰，让其具有异步回调监听功能，然后在设置监听器
 *
 * @author Daniel
 */
public class FutureTest {

    /**
     * 创建线程池
     */
    private  static final ExecutorService executorService = Executors.newFixedThreadPool(3);

    /**
     * 将线程池包装成监听线程池
     */
    private  static final ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(executorService);

    public static void main(String[] args) {
        // 提交监听异步任务
        ListenableFuture listenableFuture = listeningExecutorService.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                if (new Random().nextInt(3) == 2) {
                    throw new NullPointerException();
                }
                return 1;
            }
        });

        // 创建回调对象
        FutureCallback<Integer> futureCallback = new FutureCallback<Integer>() {

            @Override
            public void onSuccess(@Nullable Integer result) {
                System.out.println("result = " + result);
                // listeningExecutorService.shutdown();
            }

            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();
            }
        };

        // 关联异步任务和回调对象
        Futures.addCallback(listenableFuture, futureCallback, listeningExecutorService);


    }

}
